<?php
namespace App\Cas;

require_once dirname(__FILE__) . '/ResponseBody.php';

/**
 * Created by IntelliJ IDEA.
 * User: aduan
 * Date: 17/3/29
 * Time: 下午3:43
 */
class CasService
{
    /**
     * @param $ticket
     * @param $service
     * @return ResponseBody
     */
    public static function casValidate($ticket, $service)
    {

        //$cas_config['server'];
        $casValidateUrl = env('CAS_SERVER').env('CAS_VALIDATE_URI');
        $params = array(
            'ticket' => $ticket,
            'service' => $service,
            'format' => 'json'
        );
        return self::sendRequest($casValidateUrl, $params);
    }

    /**
     * @param $url
     * @param $params array(key => value)
     * @return ResponseBody
     */
    private static function sendRequest($url, $params)
    {
        $data = http_build_query($params);
        //{"serviceResponse" : {"authenticationSuccess" : {"user":"xd-huang3","attributes":{"userId":"58d028b6b760041e3d26c179","userApiKey":"5c1407ace0d37345daabf7e8d259a351","cnName":"黄贤端","email":"xd-huang3@hnair.com","mobile":"18876168892"}}}}
        //{"serviceResponse" : {"authenticationFailure" : {"code":"INVALID_TICKET","description":"请求参数错误"}}}
        //$html = file_get_contents($url."?".$data);
        $html = self::getHTTPS($url."?".$data);
        //\Log::info('$html type: ' . gettype($html));
        //\Log::info($url . '?' . $da . ': ' . $html);
        $json = json_decode(trim($html));
        $res = new ResponseBody();
        $res->setSuccess(false);

        $result = $json->serviceResponse;
        if (array_key_exists("authenticationSuccess", $result))
        {
            $success = $json->serviceResponse->authenticationSuccess;
            if($success)
            {
                $res->setSuccess(true);
                $res->setUser($success->user);
                $res->setAttributes($success->attributes);
            }
        }
        return $res;
    }

    private static function getHTTPS($url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_HEADER, false);
        //curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like G
ecko) Chrome/58.0.3029.110 Safari/537.36');
        curl_setopt($ch, CURLOPT_URL, $url);
        //curl_setopt($ch, CURLOPT_REFERER, $url);
        //curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $result = curl_exec($ch);
        //curl_close($ch);
        return $result;
    }
}

